package com.hksj.Intelligentmanagement.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.hksj.Intelligentmanagement.entity.HandNumbnessEntity;
import com.hksj.Intelligentmanagement.mapper.InsertHandNumbnessMapper;
import com.hksj.Intelligentmanagement.mapper.ReadHandNumbnessMapper;
import com.hksj.Intelligentmanagement.vo.ReadHandNumbnessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ReadHandNumbnessService {

    @Autowired
    private ReadHandNumbnessMapper readHandNumbnessMapper;

    @Autowired
    private InsertHandNumbnessMapper insertHandNumbnessMapper;

    // 自身代理对象注入
    @Autowired
    private ReadHandNumbnessService selfProxy;

    /**
     * 主流程入口方法（非事务方法，用于触发各自独立事务的方法）
     */
    public void startSync() {
        selfProxy.syncData();
    }

    /**
     * 独立事务方法，用于控制整个同步流程
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void syncData() {
        try {
            System.out.println("【syncData】当前数据源：" + DynamicDataSourceContextHolder.peek());

            String maxAprq = selfProxy.getMaxAprq(); // 从 MySQL 获取最大时间

            List<ReadHandNumbnessVo> list;

            if (StringUtils.isEmpty(maxAprq)) {
                System.out.println("【首次同步】开始全量同步数据");
                list = selfProxy.fetchFromSqlServer(null);
            } else {
                System.out.println("【增量同步】仅同步大于 " + maxAprq + " 的数据");
                list = selfProxy.fetchFromSqlServer(maxAprq);
            }

            if (list == null || list.isEmpty()) {
                System.out.println("未查询到需同步的数据");
                return;
            }

            List<HandNumbnessEntity> entityList = list.stream()
                    .map(this::convertToEntity)
                    .collect(Collectors.toList());

            selfProxy.batchInsert(entityList); // 写入 MySQL

            System.out.println("成功同步 " + entityList.size() + " 条数据");

        } catch (Exception e) {
            System.err.println("同步失败：" + e.getMessage());
            throw e;
        }
    }

    /**
     * 从 MySQL 获取最大时间（新事务）
     */
    @DS("hkmysql")
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public String getMaxAprq() {
        return insertHandNumbnessMapper.getMaxAprq();
    }

    /**
     * 从 SQL Server 查询数据（新事务）
     */
    @DS("sqlserver")
    @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true, rollbackFor = Exception.class)
    public List<ReadHandNumbnessVo> fetchFromSqlServer(String maxAprq) {
        return readHandNumbnessMapper.readAllSensors(maxAprq);
    }

    /**
     * 批量写入 MySQL（新事务）
     */
    @DS("hkmysql")
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void batchInsert(List<HandNumbnessEntity> entityList) {
        insertHandNumbnessMapper.insertHandNumbnessList(entityList);
    }

    /**
     * 查询测试方法（SQL Server）
     */
    public List<Map<String, Object>> queryTestForWN() {
        return readHandNumbnessMapper.queryTestForWN();
    }

    private HandNumbnessEntity convertToEntity(ReadHandNumbnessVo vo) {
        HandNumbnessEntity entity = new HandNumbnessEntity();
        entity.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        entity.setBlh(vo.getBlh());
        entity.setMzys(vo.getMzys());
        entity.setXshsxm(vo.getXshsxm());
        entity.setXshsid(vo.getXshsid());
        entity.setXhhsxm(vo.getXhhsxm());
        entity.setXhhsid(vo.getXhhsid());
        entity.setQxhsxm(vo.getQxhsxm());
        entity.setQxhsid(vo.getQxhsid());
        entity.setSsmc(vo.getSsmc());
        entity.setAprq(vo.getAprq());
        entity.setKssj(vo.getKssj());
        entity.setSss(vo.getSss());
        entity.setSszt(vo.getSszt());
        entity.setSsztid(vo.getSsztid());
        entity.setMzmc(vo.getMzmc());
        entity.setMzdm(vo.getMzdm());
        entity.setSex(vo.getSex());
        entity.setAge(vo.getAge());
        entity.setZdysname(vo.getZdysname());
        entity.setZdysid(vo.getZdysid());
        entity.setHzxm(vo.getHzxm());
        entity.setSsbw(vo.getSsbw());
        entity.setCwdm(vo.getCwdm());
        entity.setRoomno(vo.getRoomno());
        entity.setRoomname(vo.getRoomname());
        entity.setSsct(vo.getSsct());
        entity.setSsdm(vo.getSsdm());
        entity.setKsdm(vo.getKsdm());
        return entity;
    }
}